<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="header-center">
        <el-input v-model="searchQuery" placeholder="搜索商品名称" class="search-input" @keyup.enter="handleSearch">
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
        <el-button v-if="searchQuery" @click="resetSearch">重置</el-button>
      </div>
      <div class="header-right">
        <el-button v-if="store.logined" type="primary" @click="goToUserInfoPage">个人信息</el-button>
        <el-button v-if="store.logined" type="primary" @click="goToOrderPage">我的订单</el-button>
        <RouterLink v-if="store.logined" :to="`/shopcart/${store.userinfo.id}`" class="cart-link">
          <el-button type="primary">购物车</el-button>
        </RouterLink>
        <el-button v-else type="primary" @click="router.push('/login')">登录</el-button>
      </div>
    </div>

    <!-- 分类导航 -->
    <div class="category-nav">
      <el-button :class="{ 'active': !selectedCategory }" @click="changeCategory(null)">
        全部
      </el-button>
      <el-button v-for="category in categories" :key="category.id"
        :class="{ 'active': selectedCategory === category.id }" @click="changeCategory(category.id)">
        {{ category.name }}
      </el-button>
    </div>

    <!-- 商品列表区域 -->
    <el-row>
      <el-col :sm="12" :lg="4" v-for="(product, index) in filteredProducts" :key="product.id">
        <el-card class="product-card">
          <el-image class="product-image" :src="product.picUrl" @click="showProductDetail(product.id)" fit="cover" />
          <div class="product-info">
            <el-link type="primary" href="javascript:void(0)" @click="showProductDetail(product.id)"
              class="product-name">
              {{ product.name }}
            </el-link>
            <div class="product-price">¥{{ product.salePrice }}</div>
          </div>
          <div class="product-actions">
            <el-button type="primary" @click="addcart(product.id)">加购物车</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 空结果提示 - 修改了这一行 -->
    <el-empty v-if="filteredProducts.length === 0 && (searchQuery || selectedCategory !== null)"
      description="没有找到匹配的商品" />

    <!-- 商品详情对话框 -->
    <el-dialog v-model="dialogVisible" title="商品详情" width="50%" center>
      <div v-if="currentProduct">
        <el-descriptions title="商品信息" :column="1">
          <el-descriptions-item label="商品名称">{{ currentProduct.name }}</el-descriptions-item>
          <el-descriptions-item label="商品价格">¥{{ currentProduct.salePrice }}</el-descriptions-item>
          <el-descriptions-item label="商品描述">{{ currentProduct.description || '暂无描述' }}</el-descriptions-item>
          <el-descriptions-item label="分类ID">{{ currentProduct.cateId }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentProduct.createTime || '暂无时间' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
        layout="total, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script setup lang='ts'>
// 脚本部分保持不变
import { store } from '@/common/store'
import axios from "axios";
import { ref, onMounted, watch, computed } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router'
const router = useRouter()

// 搜索关键词
const searchQuery = ref("");
// 当前选中的分类ID（null表示全部）
const selectedCategory = ref<number | null>(null);
// 分类列表
const categories = ref<any>([]);
// 原始商品列表
const originalProducts = ref<any>([]);
//分页商品列表
const currentPageProducts = ref<any>([]);
// 对话框显示状态
const dialogVisible = ref(false);
// 当前查看的商品详情
const currentProduct = ref<any>(null);
// 当前页码
const currentPage = ref(1);
// 每页显示数量
const pageSize = ref(12);
// 总记录数
const total = ref(0);
// 过滤后的商品列表（基于搜索和分类）
const filteredProducts = computed(() => {
  // let result = [...originalProducts.value];
  let result = [...currentPageProducts.value];

  // 1. 按分类筛选
  if (selectedCategory.value !== null) {
    result = result.filter(product => product.cateId === selectedCategory.value);
  }

  // 2. 按搜索词筛选
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.trim().toLowerCase();
    result = result.filter(product =>
      product.name.toLowerCase().includes(query)
    );
  }
  return result;
});

// 加载所有商品和分类
async function loadInitialData() {
  try {
    // 并行请求分类和商品数据
    const [categoryRes, productRes] = await Promise.all([
      axios.get("/public/categorys"),
      axios.get("/public/products", {
        params: {
          categoryId: selectedCategory.value,
          page: currentPage.value,
          size: pageSize.value
        }
      })
    ]);

    categories.value = categoryRes.data.data;
    console.log(categoryRes.data.data)
    // originalProducts.value = productRes.data.records;
    currentPageProducts.value = productRes.data.data.records; // 当前页商品
    console.log(productRes.data)
    total.value = productRes.data.data.total; // 总记录数
  } catch (error) {
    console.error("加载数据失败:", error);
    ElMessage.error("加载数据失败，请重试");
  }
}

// 添加到购物车
function addcart(id: string) {
  if (!store.logined) {
    ElMessage.warning("请先登录");
    return;
  }

  let url = "/shopcartapi/" + store.userinfo.id + "/shopcarts";
  axios.post(url, { productId: id, buyCount: 1 }).then(res => {
    if (res.data.code * 1 === 200) {
      ElMessage.success("添加购物车成功");
    }
  });
}

// 处理搜索
function handleSearch() {
  const query = searchQuery.value.trim();
  if (!query) {
    ElMessage.warning("请输入搜索关键词");
    return;
  }

  //调用后端搜索接口（需后端支持）
  axios.get(`/public/products/search?query=${query}`).then(res => {
    originalProducts.value = res.data.data;
  }).catch(err => {
    console.error('搜索失败', err);
    ElMessage.error('搜索失败，请重试');
  });
  // axios.get(`/public/products/search`, {
  //   params: {
  //     query,
  //     page: currentPage.value,
  //     size: pageSize.value
  //   }
  // }).then(res => {
  //   currentPageProducts.value = res.data.data.records;
  // total.value = res.data.data.total; // 新增：获取搜索结果总记录数
  // }).catch(err => {
  //   console.error('搜索失败', err);
  //   ElMessage.error('搜索失败，请重试');
  // });
}


// 重置搜索
function resetSearch() {
  searchQuery.value = "";
  currentPage.value = 1;
  loadInitialData();
}

// 切换分类
function changeCategory(categoryId: number | null) {
  selectedCategory.value = categoryId;
  currentPage.value = 1;
  loadInitialData();
}
//订单
function goToOrderPage(){
  router.push("/order/list")
}
// 显示商品详情
async function showProductDetail(id: number) {
  try {
    // 调用后端接口获取商品详情（需后端实现 /public/products/{id} 接口）
    const res = await axios.get(`/public/products/${id}`);
    currentProduct.value = res.data.data;
    dialogVisible.value = true;
  } catch (error) {
    console.error('获取商品详情失败', error);
    ElMessage.error('获取商品详情失败，请重试');
  }
}

function handleCurrentChange(newPage: number) {
  currentPage.value = newPage;
  loadInitialData();
}

function goToUserInfoPage() {
  router.push('/info');
}

onMounted(() => {
  loadInitialData();
});
</script>

<style scoped>
/* 样式部分保持不变 */
.app-container {
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.header-left,
.header-center,
.header-right {
   display: flex;
    align-items: center;
    gap: 20px; 
}

.header-center {
  flex: 1;
  margin: 0 20px;
}

.search-input {
  width: 300px;
}

.cart-link {
  margin-left: 12px;
}

.category-nav {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.category-nav .active {
  background-color: #409eff;
  color: white;
}

.product-card {
  margin-bottom: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.product-image {
  width: 100%;
  height: 200px;
  margin-bottom: 10px;
}

.product-info {
  flex-grow: 1;
  margin-bottom: 10px;
}

.product-name {
  display: block;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-price {
  color: #f56c6c;
  font-weight: bold;
}

.product-actions {
  margin-top: auto;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>